﻿CREATE PROCEDURE [maint].[LogRestore]
@DbName [sysname], @DeviceName NVARCHAR (128), @FilePosition INT, @Type INT, @StartDate DATETIME, @FinishDate DATETIME=NULL, @RestorePoint DATETIME=NULL, @RecoverStatus BIT=NULL, @ErrorCode INT=NULL, @Output NVARCHAR (MAX)=NULL, @OutputDiagnostics BIT=0
AS
BEGIN
	SET NOCOUNT ON

	DECLARE @RC int, @ERROR int
	SET @RC = 0

	IF(@OutputDiagnostics = 1)
		BEGIN
			PRINT OBJECT_NAME(@@PROCID)
			PRINT N'	@DbName = N''' + ISNULL(@DbName,N'NULL') + ''''
			PRINT N'	@DeviceName = N''' + ISNULL(@DeviceName,N'NULL') + ''''
			PRINT N'	@FilePosition = N''' + ISNULL(CAST(@FilePosition AS nvarchar),N'NULL') + ''''
			PRINT N'	@Type = N''' + ISNULL(CAST(@Type AS nvarchar),N'NULL') + ''''
			PRINT N'	@StartDate = N''' + ISNULL(CAST(@StartDate AS nvarchar),N'NULL') + ''''
			PRINT N'	@FinishDate = N''' + ISNULL(CAST(@FinishDate AS nvarchar),N'NULL') + ''''
			PRINT N'	@RestorePoint = N''' + ISNULL(CAST(@RestorePoint AS nvarchar),N'NULL') + ''''
			PRINT N'	@RecoverStatus = N''' + ISNULL(CAST(@RecoverStatus AS nvarchar),N'NULL') + ''''
			PRINT N'	@ErrorCode = N''' + ISNULL(CAST(@ErrorCode AS nvarchar),N'NULL') + ''''
			PRINT N'	@Output = N''' + ISNULL(@Output,N'NULL') + ''''
		END
		
		UPDATE [maint].[RestoreLog]
		SET
				[FinishDate] = @FinishDate
				,[RestorePoint] = @RestorePoint
				,[RecoverStatus] = @RecoverStatus
				,[ErrorCode] = @ErrorCode
				,[Output] = @Output
				,[RestoredBy] = SUSER_SNAME()		
		WHERE  ([DbName] = @DbName)
			AND([DeviceName] = @DeviceName)
			AND([FilePosition] = @FilePosition)
			AND([Type] = @Type)
			AND([StartDate] = @StartDate);
		
		IF(@@ROWCOUNT = 0)
			INSERT INTO [maint].[RestoreLog](
				[DbName]
				,[DeviceName]
				,[FilePosition]
				,[Type]
				,[StartDate]
				,[FinishDate]
				,[RestorePoint]
				,[RecoverStatus]
				,[ErrorCode]
				,[Output]
				,[RestoredBy]
			)
			VALUES(
				@DbName
				,@DeviceName
				,@FilePosition
				,@Type
				,@StartDate
				,@FinishDate
				,@RestorePoint
				,@RecoverStatus
				,@ErrorCode
				,@Output
				,SUSER_SNAME()
			);
	
	GOTO EXIT_PROC

ERROR_HANDLER:
	IF(@RC = 0)
		SET @RC = @ERROR

EXIT_PROC:
	RETURN(@RC)
END;